//
//  ConcludeOrderVC.m
//  代理端
//
//  Created by sliver on 15/12/14.
//  Copyright (c) 2015年 sliver. All rights reserved.
//

#import "ConcludeOrderVC.h"
#import "Unit.h"
#import "WXDataService.h"
#import "PayVC.h"
#import "orderButten.h"
#import "ConcluderTableViewCell.h"
@interface ConcludeOrderVC ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate,BackViewDeleget>
{
    UITextField *telTextField;
//    UIButton *xinghaobtn;
    NSMutableArray *dataAry;
    NSString *xuanzeStr; //选项id
    NSInteger flag; // 选项的位置
    UILabel *jieLab; // 总价
    UILabel *moeyLab; //单价
    UITableView *tableview;
    NSString *numberStr;//输入的库存数量
    
    BOOL isSelect;//是否选了型号
    
    orderButten *orderbtn;
}
@end

@implementation ConcludeOrderVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    dataAry = [[NSMutableArray alloc]init];
    [self loadNav];
    [self loadmainView];
    [self postnetworking];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(productChange) name:UITextFieldTextDidChangeNotification object:telTextField];


}
-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UITextFieldTextDidChangeNotification object:telTextField];

}
-(void)productChange
{
    numberStr = telTextField.text ;
    jieLab.text =[NSString stringWithFormat:@"￥%.2f",[numberStr floatValue] * [dataAry[flag][@"price"] floatValue]];

}

-(void)loadmainView{
    
    //背景
    UIView *viewww = [[UIView alloc]initWithFrame:CGRectMake(0, 60, ScreenW, 130)];
    viewww.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:viewww];
    
    UILabel *shouhuorenLab = [[UILabel alloc]initWithFrame:CGRectMake(20, 65, 200, 20)];
//    shouhuorenLab.textColor = [UIColor grayColor];
    shouhuorenLab.text =[NSString stringWithFormat:@"联系人:%@", USER_DIC[@"company_contact_name"]];;
    shouhuorenLab.font = [UIFont systemFontOfSize:17];
    [self.view addSubview:shouhuorenLab];
    
    UILabel *nameLab = [[UILabel alloc]initWithFrame:CGRectMake(ScreenW -200, 65, 180, 20)];
    nameLab.text = USER_DIC[@"company_contact_tel"];
    nameLab.font = [UIFont systemFontOfSize:17];
//    nameLab.textColor = [UIColor grayColor];
    nameLab.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:nameLab];
    
    UILabel *addressLab = [[UILabel alloc]initWithFrame:CGRectMake(20, 90, ScreenW-40, 60)];
    addressLab.textColor = [UIColor blackColor];
    addressLab.font = [UIFont systemFontOfSize:17];
    addressLab.text =[NSString stringWithFormat:@"地址:%@",USER_DIC[@"deliver_address"]];
    addressLab.numberOfLines = 0;
    [self.view addSubview:addressLab];
    
    UIView *vieww = [[UIView alloc]initWithFrame:CGRectMake(0, 150, ScreenW, 1)];
    vieww.backgroundColor = DRINK_LIGHTGRAY_COLOR;
    [self.view addSubview:vieww];
    
    UILabel *shangpinmingchenLab = [[UILabel alloc]initWithFrame:CGRectMake(20, 151, 100, 40)];
    shangpinmingchenLab.text = _datadic[@"name"];
    shangpinmingchenLab.font = [UIFont boldSystemFontOfSize:17];
    [self.view addSubview:shangpinmingchenLab];
    
    
    moeyLab = [[UILabel alloc]initWithFrame:CGRectMake(ScreenW - 180, 151, 160, 40)];
    moeyLab.textAlignment = NSTextAlignmentRight;
//    moeyLab.backgroundColor = [UIColor redColor];
    
    moeyLab.font = [UIFont boldSystemFontOfSize:17];
    [self.view addSubview:moeyLab];
    
    //按钮
    UIButton *landBtn = [[UIButton alloc]initWithFrame:CGRectMake(60, ScreenH - 100, ScreenW - 120, 40)];
    landBtn.backgroundColor = DRINK_RED_COLOR;
    landBtn.layer.masksToBounds = YES;
    landBtn.layer.cornerRadius = 5;
    [landBtn setTitle:@"确定" forState:UIControlStateNormal];
    landBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    [landBtn addTarget:self action:@selector(clickland) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:landBtn];
    UIView *wihchview = [[UIView alloc]initWithFrame:CGRectMake(60, 270, 10, 40)];
    wihchview.backgroundColor = [UIColor whiteColor];
//    [self.view addSubview:wihchview];
    //输入数量TextField
    telTextField = [[UITextField alloc]initWithFrame:CGRectMake(60, 270, ScreenW-100, 40)];
    telTextField.delegate = self;
    telTextField.backgroundColor = [UIColor whiteColor];
    telTextField.textColor = [UIColor grayColor];
    telTextField.font = [UIFont systemFontOfSize:17];
    telTextField.placeholder = @"请输入数量";
//    telTextField.inputView = wihchview;
    telTextField.textAlignment = NSTextAlignmentLeft;
    telTextField.leftViewMode = UITextFieldViewModeAlways;
    telTextField.leftView = wihchview;
    telTextField.clearButtonMode = UITextFieldViewModeNever;
    telTextField.keyboardType = UIKeyboardTypeNumberPad;
    telTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    telTextField.returnKeyType = UIReturnKeyDone;
    telTextField.layer.masksToBounds = YES;
    telTextField.layer.cornerRadius = 5;
//    telTextField.userInteractionEnabled = NO;
    telTextField.leftView =wihchview;
    [self.view addSubview:telTextField];
    //合计
    UILabel *hejiLab = [[UILabel alloc]initWithFrame:CGRectMake(80, 340, 40, 20)];
    hejiLab.text = @"合计:";
    hejiLab.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:hejiLab];
    //金额
    jieLab = [[UILabel alloc]initWithFrame:CGRectMake(120, 340, 150, 20)];
    jieLab.tag = 666;
    jieLab.font = [UIFont boldSystemFontOfSize:21];
    [self.view addSubview:jieLab];

    //输入型号
//    UIView *withview2 = [[UIView alloc]initWithFrame:CGRectMake(60, 220, 20, 40)];
//    withview2.backgroundColor = [UIColor whiteColor];
//    [self.view addSubview:withview2];
    orderbtn = [[orderButten alloc]init ];
    orderbtn.frame = CGRectMake(60, 220, ScreenW-100, 40);
//    orderbtn.layer.masksToBounds = YES;
//    orderbtn.layer.cornerRadius = 5;
//    orderbtn.backgroundColor = [UIColor redColor];
//    [orderbtn setTitle:@"请选择型号" forState:UIControlStateNormal];
//    orderbtn.titleLabel.font = [UIFont systemFontOfSize:17];
//    orderbtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//    [orderbtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [orderbtn addTarget:self action:@selector(clickxinghaobtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:orderbtn];
    tableview = [[UITableView alloc]initWithFrame:CGRectMake(60, 270, ScreenW-100, 160)];
    tableview.delegate = self;
    tableview.dataSource = self;
    tableview.hidden = YES;
    [self.view addSubview:tableview];

    //    [tableview bringSubviewToFront:]

 }
-(void)clickxinghaobtn:(UIButton *)sender{
    telTextField.text = nil;
    jieLab.text =@"0.00";
    tableview.hidden=NO;

}
-(void)postnetworking
{
    [MyMbd addHudToView:self.view];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:_datadic[@"id_"] forKey:@"commodity_id_"];
    [WXDataService requestWithURL:@"mobile/agency/listModel.jhtml" params:params httpMethod:@"POST" block:^(id result, NSString *success, NSString *msg) {
        
        [MyMbd hidenHudFromView:self.view];
        
        BOOL suc =[success boolValue];
        if (suc == 0 ) {
            UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [deleAlertView show];
            return;
        }else if(suc == 1){
            dataAry = result[@"commodity_models"][@"listItems"];
            
            NSDictionary *dic = dataAry[0];
            moeyLab.text =[NSString stringWithFormat:@"￥%.2lf",[dic[@"price"] doubleValue]];

            [tableview reloadData];
        }
    }failblock:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];


}
#pragma mark - 点击确定
-(void)clickland{
    if(xuanzeStr.length == 0 && telTextField.text.length == 0){
        UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:@"请正确输入" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [deleAlertView show];
        return;
    }
    [self lostproduct];
    }
#pragma mark - nav
-(void)loadNav{
    self.view.backgroundColor = DRINK_LIGHTGRAY_COLOR;
    UIView *redview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 20)];
    redview.backgroundColor = DRINK_RED_COLOR;
    [self.view addSubview:redview];
    UILabel *redLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, ScreenW, 40)];
    redLab.backgroundColor = DRINK_RED_COLOR;
    redLab.text = @"下单";
    redLab.textColor = [UIColor whiteColor];
    redLab.textAlignment =  NSTextAlignmentCenter;
    redLab.font = [UIFont boldSystemFontOfSize:19];
    [self.view addSubview:redLab];
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 20,44, 44)];
    backBtn.adjustsImageWhenHighlighted = NO;
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
}
-(void)clickBack{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    
    tableview.hidden = YES;
    [telTextField resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataAry.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ConcluderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
    
    if (!cell) {
        cell = [[ConcluderTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell1"];
    }
    [cell gaveMeprice:[NSString stringWithFormat:@"￥%.2lf",[[dataAry objectAtIndex:indexPath.row][@"price"] doubleValue]] WithName:dataAry[indexPath.row][@"name"] ];
    
//    cell.textLabel.text = dataAry[indexPath.row][@"name"];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [orderbtn setTitle:dataAry[indexPath.row][@"name"] forState:UIControlStateNormal];
    [orderbtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [orderbtn gaveMprice: [NSString stringWithFormat:@"￥%.2lf",[[dataAry objectAtIndex:indexPath.row][@"price"]doubleValue] ]];
    
    tableView.hidden = YES;
    [telTextField endEditing:YES];
    xuanzeStr =[dataAry objectAtIndex:indexPath.row][@"id_"];
    flag = indexPath.row;
    moeyLab.text =[NSString stringWithFormat:@"￥%.2f",[[dataAry objectAtIndex:indexPath.row][@"price"] doubleValue ] ];
    isSelect = YES;

}
#pragma 点击确定之后再判断库存
-(void)lostproduct
{
    if ([[dataAry objectAtIndex:flag][@"stock"] intValue] < [numberStr intValue]) {
        
        NSString *stcok = [dataAry objectAtIndex:flag][@"stock"];
        UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:@"剩余库存%@",stcok] delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [deleAlertView show];
        return;
    }
    int number = [numberStr intValue] * [dataAry[flag][@"price"] intValue];
    
    if (number==0) {
        UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:@"金额为0无法下单"delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [deleAlertView show];
        return;

    }
    BackView *baview = [[BackView alloc]init];
    [baview addToview:self.view WithDeleget:self WithMessage:@"请选择支付类型" WithBtnCount:2];
    [baview changetitle:@"线下支付" righttitle:@"线上支付"];
//    [BackView addToview:self.view WithDeleget:self WithMessage:@"是否先下单后支付" WithBtnCount:2];
    


}
#pragma mark--发送网络请求
-(void)postnetwork:(NSString *)str
{
    [MyMbd addHudToView:self.view];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:str forKey:@"is_pay"];
    [params setObject:xuanzeStr forKey:@"commodity_model_id_"];
    [params setObject:telTextField.text forKey:@"count"];
    [params setObject:USER_ACCOUNT forKey:@"agency_id_"];
    [WXDataService requestWithURL:@"mobile/agency/createOrder.jhtml" params:params httpMethod:@"POST" block:^(id result, NSString *success, NSString *msg) {
        [MyMbd hidenHudFromView:self.view];
        BOOL suc =[success boolValue];
        if (suc == 0 ) {
            UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [deleAlertView show];
            return;
        }else if(suc == 1){
            if ([str isEqualToString:@"1"]) {
                PayVC *payvc = [[PayVC alloc]init];
                payvc.modalPresentationStyle = UIModalTransitionStyleCoverVertical;
                payvc.order_id = result[@"order_id_"];
                payvc.totalMoey =[NSString stringWithFormat:@"%i",[telTextField.text intValue] * [dataAry[flag][@"price"] intValue]];
                [self presentViewController:payvc animated:YES completion:nil];
            }else
            {
                [BackView addToview:self.view WithDeleget:self WithMessage:@"选择线下支付成功，请及时支付" WithBtnCount:1];
            }
            
            
        }
    }failblock:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

#pragma mark---提示框的用法
-(void)makeSureButtenClic:(UIButton *)btn withMessage:(NSString *)message
{
    if ([message isEqualToString:@"选择线下支付成功，请及时支付"]) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }else if ([message isEqualToString:@"请选择支付类型"]){
        if (btn.tag==0) {
            [self postnetwork:@"2"];
        }else{
            [self postnetwork:@"1"];
        }
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (!isSelect) {
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请先选择型号" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [telTextField endEditing:YES];
        [alter show];
    }
}

@end
